<?php
/**
 * Thumbnail
 *
 * @author fusq
 */
$LIB_PATH='/opt/akimimi_common/';
require_once $LIB_PATH.'config.php';
require_once $LIB_PATH.'lib/thumbnail/class.asido.php';
require_once $LIB_PATH.'lib/thumbnail/class.driver.gd.php';
class Thumbnail{

    private $sizes = array(400,250,200,160,120,100,80,60);
    private $copySizes = array(800,600);
    
    private $proSuffix = "jpg";
    
    private function initDbConnection() {       
         $db_host = DB_HOST;
         $db_user = DB_USER;
         $db_pw = DB_PWD;
         $db_name = DB_PREFIX . "_" . DB_NAME;
         $link = mysql_connect($db_host,$db_user,$db_pw);
         if(!$link){
             echo "Can't connect to mysql server.";
             exit();
         }
         mysql_query("USE `$db_name`");
         return $link;
         
    }
    /**
     * upload product image
     */
    public function uploadProImage(){
        echo "Initializing...\n";
        $productImagePath = P_IMAGE_PATH;
        $thumbnailImagePath = THUMBNAIL_P_PATH;
        //read source image
        $d = dir($productImagePath);
        $sourceArr = array();
        while($f = $d->read()){
            $temp = strtolower($f);          
            if(is_file("$d->path/$f") && strpos($temp,$this->proSuffix)){
                $sourceArr[] = $f;
            }
        }
        $d->close();
        $imageDetails = $this->getImageDetail($sourceArr);
        $count = count($imageDetails);
        if($count > 0){
        	echo "get blank data\n";
            //get blank data from database
            $sqlSelect = "select id,folder from product_images where item_id is null and is_delete = 0 order by id asc limit $count";
            $link = $this->initDbConnection();
            $result = mysql_query($sqlSelect);
            $ids = array();
            //$productImg = array();
            //$productRemovedItem = array();
            //$productIds = array();
            while($row = mysql_fetch_array($result,MYSQL_NUM)){
                $ids[] = array($row[0],$row[1]);
            }
            if(count($ids) != $count){
                echo "Record in db is not enough.\n";
                exit();
            }
            Asido::driver('gd');
            echo "start init image\n";
            foreach($imageDetails as $key => $imageDetail){
               $id = $ids[$key];
               $targetFolder = $thumbnailImagePath . $id[1];
               if(!file_exists($targetFolder)){
                   mkdir($targetFolder,0777,true);
               }
               //get target file name
               if($imageDetail["suffix"] == "item"){
               	    $productItem = $this->getProductItem($imageDetail['id']);
               }             
               if(!empty($productItem)){
                   $productIdTemp = $productItem['pid'];
                   $itemIdTemp = $productItem['id'];
                   $sort = $imageDetail['sort'];
                   $default = $imageDetail['default'];
                   $targetFileName =  $productIdTemp . "_" . $itemIdTemp . "_" . $sort;
                   echo "check exist (pid:$productIdTemp iid:$itemIdTemp)\n";
                   $folederTemp = $this->getProImageByTargetFile($productIdTemp,$itemIdTemp,$targetFileName);
                   if(!empty($folederTemp)){
                   	    echo "has been exist\n";
                   	    $targetFolder = $thumbnailImagePath . $folederTemp;
                        if(!file_exists($targetFolder)){
                            mkdir($targetFolder,0777,true);
                        }                   	    
                   }
                   echo "create thumbnail(iid:$itemIdTemp)\n";
                   //init thumbnail by size
                   foreach($this->sizes as $size){
                       $img = Asido::image($productImagePath . '/'. $imageDetail['source'], $targetFolder.$targetFileName . "_" . $size . "." . $this->proSuffix);
                       Asido::resize($img, $size, $size, ASIDO_RESIZE_STRETCH);
                       $img->save(ASIDO_OVERWRITE_ENABLED);
                   }
                   echo "create copy file(iid:$itemIdTemp)\n";
                   //copy source image file
                   foreach($this->copySizes as $copySize){
                   	   copy($productImagePath . '/'. $imageDetail['source'],$targetFolder.$targetFileName . "_" . $copySize . "." . $this->proSuffix);
                   }
                   if(empty($folederTemp)){
                       $this->updateProImage($id[0],$itemIdTemp,$productIdTemp,$targetFileName,$sort,$default);                  	
                   }
               }
            }
            $this->setDefaultItemImage();
            
            mysql_close($link);
        }
        echo "Finish\n";
    }
    
    public function setDefaultItemImage(){
    	
		$sql = "select id from product_items where is_delete = 0 ";
		$result = mysql_query($sql);
		
		while($row = mysql_fetch_array($result,MYSQL_NUM)){
		     $id = $row[0];
		     if( $id > 0){
		     	
			        //set null 
			        $sql4 = "update product_items set default_item_image_id = null where id = $id";
			        mysql_query($sql4);
			        //set default image id  
			        		     	
			        $sql2 = "select id from product_images where is_delete=0 and default_item_image = 1 and item_id = $id";
			        $result2 = mysql_query($sql2);
			        while($row2 = mysql_fetch_array($result2,MYSQL_NUM)){
			            $imageId = $row2[0];
			            if(!empty($imageId) && $imageId > 0){
			                $sql3 = "update product_items set default_item_image_id = $imageId where id = $id";
			                mysql_query($sql3);
			            }  
			        }
		     }
		}    	
    }
    
    public function setDefaultItemImageById($itemId){
             if(!empty($itemId) && $itemId > 0){
                    //set default image id                                     
                    $sql = "select id from product_images where is_delete=0 and default_item_image = 1 and item_id = $itemId";
                    $result = mysql_query($sql);
                    while($row = mysql_fetch_array($result,MYSQL_NUM)){
                        $imageId = $row[0];
                        if(!empty($imageId) && $imageId > 0){
                            $sql2 = "update product_items set default_item_image_id = $imageId where id = $itemId";
                            mysql_query($sql2);
                        }  
                    }
             }
     
    }    
    
    private function updateProImage($id,$itemId,$productId,$targetName,$sort,$default){
        
        if($default == "1"){
            $sqlUpdateDefault = "update product_images set `default_item_image` = 0  where `product_id` = $productId  and `item_id` = $itemId and `is_delete` = 0 ";
            mysql_query($sqlUpdateDefault);            
        }
    	if($default == "1"){
    		$sqlUpdate = "update product_images set `product_id` = $productId , `item_id` = $itemId , `name` = '$targetName', `sort_order` = $sort , `default_item_image` = 1 ,`modified` = now() where `id` = $id ";          		
    	}else{
    		$sqlUpdate = "update product_images set `product_id` = $productId , `item_id` = $itemId , `name` = '$targetName', `sort_order` = $sort , `modified` = now() where `id` = $id ";               
    	}
        mysql_query($sqlUpdate);  
          	
    }
    
    private function getProImageByTargetFile($productId,$itemId,$targetName){
    	$sqlSelect = "select folder from product_images where is_delete = 0 and product_id = $productId and item_id = $itemId and name = '$targetName' ";
        $result = mysql_query($sqlSelect);
        $folder = ""; 
        while($row = mysql_fetch_array($result,MYSQL_NUM)){
            $folder = $row[0];
        }     
        return $folder;
    }
    
    private function getImageDetail($sourceArr){
    	$resultArr = array();
    	$length = strlen($this->proSuffix) + 1;
    	foreach($sourceArr as $source){
    		$result = array();
    		$name = substr($source,0,-$length);
    		$temp = split("_",$name);
    		if(strtolower(trim($temp[0])) == "i"){
    			$result = array(
    			             "suffix" => "item",
    			             "id" => trim($temp[1]),
    			             "default" => trim($temp[2]),
    			             "sort" => trim($temp[3]),
    			             "source" => $source
    			         );
    			$resultArr[] = $result;
    		} 
    		if(strtolower(trim($temp[0])) == "g"){
    			$gIds = split("-",trim($temp[1]));
    			//$sorts = split("-",trim($temp[2]));
    			//$index = 0;
    			foreach($gIds as $gId){
	                $result = array(
	                             "suffix" => "item",
	                             "id" => trim($gId),
	                             "default" => trim($temp[2]),
	                             "sort" => trim($temp[3]),
	                             //"sort" => trim($sorts[$index]),
	                             "source" => $source
	                         );    
	                $resultArr[] = $result;		
	                //$index++;		
    			}
    		}
    	}
    	return $resultArr;
    }
//    private function setDefaultProItem($productIds){
//        foreach($productIds as $productId){
//            $sqlSelect1 = "select count(*) as count from product_images where product_id = $productId and default_item = 1 and is_delete = 0 ";
//            $result1 = mysql_query($sqlSelect1);
//            $count = 0;
//            while($row1 = mysql_fetch_array($result1,MYSQL_NUM)){
//                $count = $row1[0];
//            }
//            if($count == 0){
//                $sqlSelect2 = "select min(id) as id from product_images where product_id = $productId and is_delete = 0";
//                $result2 = mysql_query($sqlSelect2);
//                $id = 0;
//                while($row2 = mysql_fetch_array($result2,MYSQL_NUM)){
//                    $id = $row2[0];
//                }
//                $sqlUpdate = "update product_images set default_item = 1 where id = $id";
//                mysql_query($sqlUpdate);
//            }
//        }
//    }

//    private function setDefaultProItemImage($productItems){
//        foreach($productItems as $productItem){
//            $sqlSelect1 = "select count(*) as count from product_images where item_id = $productItem and default_item_image = 1 and is_delete = 0 ";
//            $result1 = mysql_query($sqlSelect1);
//            $count = 0;
//            while($row1 = mysql_fetch_array($result1,MYSQL_NUM)){
//                $count = $row1[0];
//            }
//            if($count == 0){
//                $sqlSelect2 = "select min(id) as id from product_images where item_id = $productItem and is_delete = 0";
//                $result2 = mysql_query($sqlSelect2);
//                $id = 0;
//                while($row2 = mysql_fetch_array($result2,MYSQL_NUM)){
//                    $id = $row2[0];
//                }
//                $sqlUpdate = "update product_images set default_item_image = 1 where id = $id";
//                mysql_query($sqlUpdate);
//            }
//        }
//    }

//    public function removeProImage(){
//        echo "Starting...\n";
//        $dirname = DELETE_IMG_PATH;
//        if ($handle = opendir($dirname)) {
//            while(false !== ($file = readdir($handle))){
//                if(($file != ".") && ($file != "..")) {
//                    if(strpos($file , ".csv") != false){
//                        $csvPath = DELETE_IMG_PATH . "/" . $file;
//                        $name = substr($file, "0" , strlen($file)-4);
//                        $folderNames = explode("-", $name);
//                        if(count($folderNames) == 2){
//                            $folder1 = $folderNames[0];
//                            $folder2 = $folderNames[1];
//                            $handle2 = fopen ( $csvPath, "r" );
//                            $row = 1;
//                            while ( $data = fgetcsv ( $handle2, 0, "," ) ) {
//                                if ($row > 1) {
//                                    $urlTitle = $data[0];
//                                }
//                                $row++;
//                            }
//                            fclose ( $handle2 );
//                        }
//                    }
//                }
//            }
//        }
//        echo "Finish\n";
//    }

//    public function removeProImage(){
//        echo "Starting...\n";
//        $dirname = DELETE_IMG_PATH;
//        if ($handle = opendir($dirname)) {
//            while(false !== ($file = readdir($handle))){
//                if(($file != ".") && ($file != "..")) {
//                    if(strpos($file , ".csv") != false){
//                        $csvPath = DELETE_IMG_PATH . "/" . $file;
//                        $handle2 = fopen ( $csvPath, "r" );
//                        $row = 1;
//                        while ( $data = fgetcsv ( $handle2, 0, "," ) ) {
//                            if ($row > 1) {
//                                $img = $data[0];
//                                $folders = explode("/", $img);
//                                $this->removeProductImage($folders);
//                            }
//                            $row++;
//                        }
//                        fclose ( $handle2 );
//                    }
//                }
//            }
//        }
//        echo "Finish\n";
//    }

    public function removeProImage(){
        echo "Starting...\n";
        $removedProImgCsv = "removedproimg-" . date('dmY') . ".csv";
        $csvPath = P_IMAGE_PATH . "/" . $removedProImgCsv;
        if(file_exists($csvPath)){
            $handle = fopen ( $csvPath, "r" );
            $row = 1;
            while ( $data = fgetcsv ( $handle, 0, "," ) ) {
                if ($row > 1) {
                    $img = $data[0];
                    $folders = explode("/", $img);
                    $this->removeProductImage($folders);
                }
                $row++;
            }
            fclose ( $handle );
        }
        echo "Finish\n";
    }

    private function getProductItem($productItemId){  
    	if(empty($productItemId)){
    		$productItemId = 0;
    	}     
        $param = trim($productItemId);
        $param = mysql_escape_string($param);
        $sql = "select pi.id,p.id as pid,p.url_title from products p ,product_items pi where p.id = pi.product_id and pi.is_delete = 0 and pi.id = $param";
        echo $sql . "\n";
        $result = mysql_query($sql);
        $item = mysql_fetch_assoc($result);
        return $item;
    }

//    private function updateProductImage($productId,$itemId,$name,$id,$productRemovedItem){
//        if(!in_array($itemId, $productRemovedItem)){
//             $sqlDelete = "update product_images set `is_delete` = 1 , `modified` = now() where `product_id` = $productId  and  `item_id` = $itemId ";
//             mysql_query($sqlDelete);
//        }
//        $sqlUpdate = "update product_images set `product_id` = $productId , `item_id` = $itemId , `name` = '$name' , `modified` = now() where `id` = $id ";       
//        mysql_query($sqlUpdate);
//    }

    private function removeProductImage($folders){
        $folder = "/" . trim($folders[1]) . "/" . trim($folders[2]) . "/";
        $urlTitle = trim($folders[3]);
        $folder = mysql_escape_string($folder);
        $urlTitle = mysql_escape_string($urlTitle);
        $sql = "select * from product_images where lower(name) like '" . strtolower($urlTitle . "_%") . "' and lower(folder) = '" . strtolower($folder) . "'";
        $link = $this->initDbConnection();
        $result = mysql_query($sql);
        $rows = array();
        $ids = array();
        while ($row = mysql_fetch_assoc($result)) {
            $rows[] = $row;
            $ids[] = $row['id'];
        }
        //remove image and update db
        if(!empty($rows)){
            foreach($rows as $data){
                //remove image
                $folder = $data["folder"] . $data["name"];
                foreach($this->sizes as $size){
                    $imagePath = THUMBNAIL_P_PATH . $folder . "_" . $size . "." . $this->proSuffix;
                    if(file_exists($imagePath)){
                        unlink($imagePath);
                    }
                }
                foreach($this->copySizes as $size){
                    $imagePath = THUMBNAIL_P_PATH . $folder . "_" . $size . "." . $this->proSuffix;
                    if(file_exists($imagePath)){
                          unlink($imagePath);
                    }
                }                 
                //update db
                $itemId = $data["id"];
                $sqlUpdate = "update product_images set product_id = null, item_id = null, name = null,  
                              default_item_image = 0, is_delete = 0, modified = now(), created = now()
                              where id = $itemId ";
                mysql_query($sqlUpdate);
            }
        }
        mysql_close($link);
    }

    public function removeProductImageById($id){
        $sqlSelect = "select * from product_images where id = $id and is_delete = 0";
        $sqlUpdate = "update product_images set product_id = null, item_id = null, name = null,   
                     default_item_image = 0, is_delete = 0, modified = now(), created = now() 
                     where id = $id ";
        $link = $this->initDbConnection();
        $result = mysql_query($sqlSelect);
        $productImage = mysql_fetch_assoc($result);
        if(!empty($productImage)){
            //remove image
            $folder = $productImage['folder'] . $productImage['name'];
            foreach($this->sizes as $size){
                $imagePath = THUMBNAIL_P_PATH . $folder . "_" . $size . "." . $this->proSuffix;
                if(file_exists($imagePath)){
                      unlink($imagePath);
                }
            }
            foreach($this->copySizes as $size){
                $imagePath = THUMBNAIL_P_PATH . $folder . "_" . $size . "." . $this->proSuffix;
                if(file_exists($imagePath)){
                      unlink($imagePath);
                }
            }            
            //update db
            mysql_query($sqlUpdate);
        }
        mysql_close($link);       
    }
    
    public function uploadOneProductImage($productId,$itemId,$sort,$default,$sourceFile){
        $thumbnailImagePath = THUMBNAIL_P_PATH;
        if(!empty($productId) && !empty($itemId)){
            $sqlSelect = "select id,folder from product_images where item_id is null and is_delete = 0 order by id asc limit 1";
            $link = $this->initDbConnection();
            $result = mysql_query($sqlSelect);
            $row = mysql_fetch_assoc($result);
            if(!empty($row)){
                $id = $row['id'];
                $folder = $row['folder'];
                $targetFolder = $thumbnailImagePath . $folder;
                $targetFileName =  $productId . "_" . $itemId . "_" . $sort;
                if(!file_exists($targetFolder)){
                   mkdir($targetFolder,0777,true);
                }     
                //init thumbnail by size
                Asido::driver('gd');
                foreach($this->sizes as $size){
                   $img = Asido::image($sourceFile, $targetFolder.$targetFileName . "_" . $size . "." . $this->proSuffix);
                   Asido::resize($img, $size, $size, ASIDO_RESIZE_STRETCH);
                   $img->save(ASIDO_OVERWRITE_ENABLED);
                }
                //copy source image file
                foreach($this->copySizes as $copySize){
                   copy($sourceFile,$targetFolder.$targetFileName . "_" . $copySize . "." . $this->proSuffix);
                }                
                $this->updateProImage($id,$itemId,$productId,$targetFileName,$sort,$default); 
                $this->setDefaultItemImageById($itemId);                             
            }
            mysql_close($link); 
        }
    }

    
}
